﻿package com.agileai.miscdp.hotweb.generator.query;

import java.io.File;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import com.agileai.miscdp.NoOpEntityResolver;
import com.agileai.miscdp.hotweb.generator.Generator;
import com.agileai.util.XmlUtil;
/**
 * SQLMap配置代码生成器
 */
public class QMSqlMapCfgGenerator implements Generator{
	private String sqlMapFileName = null;
	private String configFile = null;
	private String encoding = "UTF-8";
	public void generate() {
		try {
	        SAXReader saxReader = new SAXReader();
	        saxReader.setEntityResolver(new NoOpEntityResolver());
	        saxReader.setIncludeExternalDTDDeclarations(false);
	        saxReader.setValidation(false);
	        Document document = saxReader.read(new File(configFile));
	        String resourceNodePath = "//sqlMapConfig/sqlMap[@resource='sqlmap/"+sqlMapFileName+".xml']";
	        Node resourceNode = document.selectSingleNode(resourceNodePath);
	        if (resourceNode != null){
	        	resourceNode.getParent().remove(resourceNode);
	        }
        	Element sqlMapConfig = (Element)document.selectSingleNode("//sqlMapConfig");
        	Element newResElement = sqlMapConfig.addElement("sqlMap");
        	newResElement.addAttribute("resource","sqlmap/"+sqlMapFileName+".xml");
        	XmlUtil.writeDocument(document, encoding, configFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setSqlMapFileName(String sqlMapFileName) {
		this.sqlMapFileName = sqlMapFileName;
	}

	public void setConfigFile(String configFile) {
		this.configFile = configFile;
	}
}
